const { Service } = require("egg");

class RoleService extends Service {
    /**
     * 根据用户id，查找角色
     * @param {string} uid 用户id
     */
    async readByUid(uid) {
        let sql = `
            select id as rid, name as rname
            from role as r
            join r_user_role as rur on r.id = rur.rid
            where rur.uid = ?        
        `;
        let params = [uid];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 角色列表
     */
    async readList() {
        let sql = "select * from role";
        let res = await this.app.mysql.query(sql);
        return res;
    }

    /**
     * 根据角色名称查找角色
     * @param {string} name 角色名称
     */
    async findByName(name) {
        let sql = "select * from role where name = ?";
        let params = [name];
        let res = await this.app.mysql.query(sql, params);
        return res[0];
    }

    /**
     * 添加角色
     * @param {object} role 角色信息
     */
    async add({ name }) {
        // 查看是否存在
        const role = await this.findByName(name);
        if (role) this.ctx.cast(403, "角色已存在");
        // 保存到数据库
        await this.app.mysql.query(
            "insert into role (id, name) values (?, ?)",
            [this.ctx.helper.uuid(), name]
        );
    }
}

module.exports = RoleService;
